 <#import "inc/macro-page.html" as panel>
<#import "macro-filter-card-box.html" as seachpanel>
<#escape x as x?html>
<@panel.header "关键岗位轮岗混岗预警" "">
</@panel.header>
<@panel.body>
<!-- Bread crumb -->
<div class="row page-titles">
    <div class="col-md-5 align-self-center">
        <h3>关键岗位轮岗混岗预警</h3> </div>
    <div class="col-md-7 align-self-center">
        <div class="page-nav-bar">
           <button class="btn btn-inverse btn-click-bind" data-sign="11" disabled>轮岗预警</button>
           <button class="btn btn-info btn-click-bind" data-sign="12">混岗预警</button>
        </div> 
    </div>
</div>
<!-- End Bread crumb -->
<!-- Container fluid  -->
<div class="container-fluid">
    <!-- Start Page Content -->                
    <div class="row">
        <div class="col-lg-12">
            <div class="card">
 				<div class="custom-card-header quick-bar">
					<div class="hint">轮岗预警</div>
					<@seachpanel.filterbox></@seachpanel.filterbox>
					    <button id="id-export-file" type="button" class="btn btn-dark btn-outline btn-sm m-l-10" title="导出"><i class="fa fa-share-square-o"></i></button>
					</div>                	
                <div class="card-body">
              <!-- 
              <div class="row m-t-20">
                 <div class="col-lg-12">
                    <div class="row">
                     	<div class="col-md-3">
                     		<select class="form-control">
                     			<option value="">请选择单位</option>
                     		</select>
                     	</div>
                     	<div class="col-md-3">
                     		<select class="form-control">
                     			<option value="">请选择部门</option>
                     		</select>
                     	</div>
                     	<div class="col-md-3">
                     		<select class="form-control">
                     			<option value="">请选择专业</option>
                     		</select>
                     	</div>
                     	<div class="col-md-3">
                     		<select class="form-control">
                     			<option value="">请选择岗位</option>
                     		</select>
                     	</div>
                    </div>
                 </div>
              </div>
              -->
                    <!-- Nav tabs -->
                    <ul class="nav nav-tabs m-t-30" role="tablist">
                        <li class="nav-item"> <a class="nav-link active" data-toggle="tab" href="#id-tab-analysis" role="tab"><span class="hidden-xs-down">分析对比</span></a> </li>
                        <li class="nav-item"> <a class="nav-link" data-toggle="tab" href="#id-tab-profile" role="tab"><span class="hidden-xs-down">具体数据</span></a> </li>
                    </ul>
                    <!-- Tab panes -->
                    <div class="tab-content tabcontent-border">
                        <div class="tab-pane active" id="id-tab-analysis" role="tabpanel">
			                <div class="row m-t-30">
			                    <!-- 
			                	<div class="col-lg-12 p-t-10 p-b-30 text-center"><h3>XXX单位XXX部门XXX专业XXX岗位</h3></div>
			                	-->
			                	<div class="col-lg-6">
			                		<div id="id-fair-chart" style="height: 480px"></div>
			                	</div>
			                	<div class="col-lg-6">
			                		<div id="id-unfair-chart" style="height: 480px"></div>
			                	</div>
			                </div>
			                <div id="id-clone-area"></div>
                        </div>
                        <div class="tab-pane" id="id-tab-profile" role="tabpanel">
    					  <div class="row m-t-30">
        						<div class="col-lg-12">
		                           <table id="id-user-table" class="table table-bordered content-center"  cellspacing="0">
		                               <thead>
		                                   <tr>
		                                       <th>岗位</th>
		                                       <th>ERP编号</th>
		                                       <th>姓名</th>
		                                       <th>年龄</th>
		                                       <th>上岗时间</th>
		                                       <th>在岗时长</th>
		                                       <th>轮岗年限要求</th>
		                                       <th>距离轮岗年限</th>
		                                   </tr>
		                               </thead>
		                            </table>
        						</div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <!-- End PAge Content -->
</div>
<!-- End Container fluid  -->
</@panel.body>
<@panel.footer>
<script type="text/javascript" src="${ROOT}/mind/js/plugins/alangyun-filterbox.js"></script>
<script type="text/javascript" src="${ROOT}/mind/js/lib/datatables/datatables.min.js"></script>
<script type="text/javascript" src="${ROOT}/mind/js/lib/datatables/jquery.dataTables.zh-CN.js"></script>
<script type="text/javascript" src="${ROOT}/mind/js/lib/echart/echarts.min.5.4.0.js"></script>
<script type="text/javascript">
	// word导出事件
	document.getElementById('id-export-file').addEventListener('click', function() {
		// Ensure echarts charts have finished rendering
		setTimeout(() => {
			var charts = document.querySelectorAll('canvas');
			charts.forEach(chart => {
				var dataURL = chart.toDataURL();
				var imgTag = '<img src="' + dataURL + '" width="500" />';
				chart.insertAdjacentHTML('beforebegin', imgTag);
				chart.style.display = 'none'; // Hide the original canvas
			});

			// Create a temporary container for the export
			var exportContainer = document.createElement('div');
			exportContainer.id = 'export-container';
			exportContainer.style.width = '100%';

			// Clone ECharts charts
			var chartContainer = document.getElementById('id-fair-chart').cloneNode(true);
			exportContainer.appendChild(chartContainer);

			var chartContainers = document.getElementById('id-unfair-chart').cloneNode(true);
			exportContainer.appendChild(chartContainers);

			// Clone user table and add border class

			var clonedTable = document.getElementById('id-user-table').cloneNode(true);
// 直接添加内联样式到每个th和td元素
			clonedTable.querySelectorAll('th, td').forEach(function(cell) {
				cell.style.border = '1px solid #000';
				cell.style.borderCollapse = 'collapse'; // 注意：borderCollapse是CSS属性，不能作为内联样式设置，但这里为了示例而写
				cell.style.textAlign = 'center';
			});
			exportContainer.appendChild(clonedTable);

			// Convert the export container's HTML to a Word document
			var htmlHeader = `
          <!DOCTYPE html>
          <html>
          <head>
            <style>
               table, th, td {
                   border: 1px solid #000;
                   text-align: center;
                   border-collapse: collapse;
               }
            </style>
          </head>
          <body>`;
			var htmlFooter = `
          </body>
          </html>`;
			var htmlContent = htmlHeader + exportContainer.innerHTML + htmlFooter;

			var blob = new Blob([htmlContent], { type: 'application/msword' });
			var url = URL.createObjectURL(blob);
			var a = document.createElement('a');
			a.href = url;
			a.download = '轮岗预警.doc';
			a.click();
			URL.revokeObjectURL(url);

			// Clean up by removing the temporary container
			exportContainer.remove();

			// Revert changes made to the document for export
			charts.forEach(chart => {
				chart.previousSibling && chart.previousSibling.remove();
				chart.style.display = 'block'; // Restore the original canvas
			});
		}, 1000); // Adjust the timeout as needed to ensure charts have rendered
	});
$(document).ready(function(){
	
	$(".btn-click-bind").click(function() {
		  var val = $(this).data("sign");
		  var ctx = "/w/pivotal";
		  if(12===val){
			  ctx = "/w/pivotal12";
		  }
		  window.location.href="${ROOT}" + ctx;
	});

	//分析图
	var fairChart = echarts.init(document.getElementById("id-fair-chart"), null, {
		      renderer: 'canvas',
		      useDirtyRect: false
		    });
	var unfairChart = echarts.init(document.getElementById("id-unfair-chart"), null, {
	      renderer: 'canvas',
	      useDirtyRect: false
	    });
	var convertToChartView = function(myChart, title, data, color, fair){
		if(!data.sums||data.sums.length==0)
			return;
		
		var values =[];
		var colors =[];
		var yData = [];
		var sum = 0
		
		data.sums.forEach(item=>{
			var value = fair? item.fair: item.unfair;
			yData.push(item.name);
			values.push({
				value: value, 
					label: {
					show: true,
					position: 'right',
					fontSize: 14,
					fontWeight: "bold"
				}
			 });
			colors.push(color);
			sum += value;
		})
	    
	    var option = {
	      color: colors,
		  tooltip: {
		    show: false
		  },
		  title: {
			  text: title,
			  left: 'center'
		  },
		  yAxis: [
		    {
		      type: 'category',
		      data: yData // ['1年', '2年', '3年', '4年', '5年及以上']
		    }
		  ],
		  grid: {
			  left: '110px'
		  },
		  xAxis: [
		    {
		      type: 'value',
		      axisLabel: {
		    	  show: false
		      },
		      splitLine: {show: false}
		    }
		  ],  
		  graphic: [{
		      type: 'group',
		      left: 'right',
		      top: 'center',
		      children: [
		        {
		          type: 'circle',
		          z: 100,
		          left: 'center',
		          top: 'middle',
		          shape: {
		            r: 45
		          },
		          style: {
		            fill: color
		          }
		        },
		        {
		          type: 'text',
		          z: 100,
		          left: 'center',
		          top: 'middle',
		          style: {
		            fill: '#fff',
		            width: 220,
		            overflow: 'break',
		            text: sum,
		            font: '22px Microsoft YaHei'
		          }
		        }
		      ]
		    }
	      ],
		  series: [
		    {
		      type: 'bar',
		      emphasis: {
		        focus: 'series'
		      },
		      data: values
		    }
		  ]
		};

	    if (option && typeof option === 'object') {
	      myChart.setOption(option);
	    }

	    window.addEventListener('resize', myChart.resize);
	}
	// 用户数据
	var $userTable = null;
	var dataToTableView = function(mydata){
		if(!mydata.users || mydata.users.length==0)
			return;
				
		if($userTable) {
			$userTable.fnClearTable();
			$userTable.fnDestroy();
		}
		
		$userTable = $("#id-user-table").dataTable({
		    "ordering":false,
		    "searching": false,
		    "bFilter":false,
		    "info": false,
		    "paging": false,
		    'bAutoWidth':false,
		    "bDestroy" : true,
		    "aoColumns": [
		    	{'mData': 'job', sWidth: '100px', defaultContent: '' },
		    	{'mData': 'id', sWidth: '100px', defaultContent: '' },
		    	{'mData': 'name', sWidth: '100px', defaultContent: '' },
		    	{'mData': 'age', sWidth: '100px', defaultContent: '' },
		    	{'mData': 'jobDate', sWidth: '100px', defaultContent: '' },
		    	{'mData': 'years', sWidth: '100px', defaultContent: '' },
		    	{'mData': 'yearLimit', sWidth: '100px', defaultContent: '' },
		    	{'mData': 'remainYears', sWidth: '100px', defaultContent: '' }
		    ],	
		    "data":mydata.users
		});
		$userTable.fnDraw();
	};

    // 导出事件绑定
    // $('#id-export-file').click(function(){
    // 	$('.nav-tabs .nav-item a[href="#id-tab-analysis"]').tab("show");
    // 	var cloneData = $('#id-user-table').clone("true");
    // 	$('#id-clone-area').append(cloneData);
	//
    // 	var pdfCanvas = $.fn.pdfcanvas({
    // 		title: '关键岗位轮岗预警',
    // 		keywords: '单位和部门：；岗位类别：'
    // 	})
    // 	pdfCanvas.addDom(document.getElementById("id-tab-analysis"));
    // 	pdfCanvas.print();
	//
    // });
    
    //初始化过滤面板
    $.post('${ROOT}/w/treeNav',function(data, status){
    	if(data.code==="ok"){
			$.fn.filterBox({
				data: data.data,
				onsubmit: function(form, data){
				    $.post('${ROOT}/w/sumpPivo',data,function(data, status){
				    	if(data&& data.code === 'ok'){
				    		if(data.data) {
				    	    	$('.nav-tabs .nav-item a[href="#id-tab-analysis"]').tab("show");
				        		convertToChartView(fairChart, "未超限人数",  data.data, '#007470', true);
				        		convertToChartView(unfairChart, "超限人数",  data.data, '#ef5350', false);
				        		dataToTableView(data.data);
				    		}else {
				    			toastr.error("未查到人岗适配资料");
				    		}
				    	} else {
				    		toastr.error(data?data.desc:"获取人岗适配资料失败");
				    	}
				    }, 'json');
				}
			})
    	}
    });
    //初始提取数据
    $.post('${ROOT}/w/sumpPivo',function(data, status){
    	if(data.code==="ok"){
    		convertToChartView(fairChart, "未超限人数",  data.data, '#007470', true);
    		convertToChartView(unfairChart, "超限人数",  data.data, '#ef5350', false);
    		dataToTableView(data.data);
    	}
    });
});
</script>
</@panel.footer>
</#escape>